<template>
  <div>
    <small class="text-warning">完善还款信息能够确保系统在保金额的准确性</small>
    <div class="mt-3 d-flex justify-content-between">
      <div style="font-size: 1.1rem">
        在保金额：
        <span class="text-primary">{{ leftFunds }} 万元</span>
      </div>
      <div>
        <el-button icon="el-icon-refresh" @click="getData()">刷新</el-button>
        <el-button
          icon="el-icon-plus"
          @click="handleEdit()"
          v-if="+related.load_beh_status !== 6 && hasPlan"
        >
          登记
        </el-button>
      </div>
    </div>

    <template v-if="!idsData.length" v-loading="loading">
      <div class="mt-2 p-5 text-center text-muted border rounded bg-light">
        暂无数据
        <span class="text-danger" v-if="!hasPlan">（请先登记还款计划）</span>
      </div>
    </template>

    <div v-for="item of idsData" :key="item.id" v-loading="loading">
      <div class="text-muted my-2">
        本期应还时间：
        <span class="text-success">
          {{ $utils.dateFormat(item.info.pay_time, 'yyyy年MM月dd日') }}
        </span>
        &nbsp;&nbsp;&nbsp; 本期应还本金：
        <span class="text-success">{{ item.info.capital }} 元</span>
        &nbsp;&nbsp;&nbsp; 剩余应还余额：
        <span class="text-success">
          {{ sub(item.info.capital, item.info.repay_funds_total) }} 元
        </span>
      </div>
      <table class="table table-bordered table-sm bg-white table-vertical-middle text-center mb-4">
        <colgroup>
          <col width="15%" />
          <col width="17%" />
          <col width="15%" />
          <col width="15%" />
          <col width="23%" />
          <col width="15%" />
        </colgroup>
        <thead>
          <tr>
            <th>还款日期</th>
            <th>还款金额（元）</th>
            <th>登记人</th>
            <th>登记时间</th>
            <th>备注</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(d, index) in item.data" :key="index">
            <td>{{ d.repay_time }}</td>
            <td>{{ d.repay_funds }}</td>
            <td>{{ d.submit_person_name }}</td>
            <td>{{ d.create_time }}</td>
            <td>{{ d.remark }}</td>
            <td>
              <el-button type="text" v-if="related.load_beh_status !== 6" size="small">
                <i class="fa fa-edit" @click="handleEdit(d)"></i>
              </el-button>

              <el-button type="text" v-if="related.load_beh_status !== 6" size="small">
                <i class="fa fa-trash text-danger" @click="handleDelete(d)"></i>
              </el-button>

              <el-button type="text" size="small">
                <i class="fa fa-search" @click="handleView(d)"></i>
              </el-button>
            </td>
          </tr>
          <tr>
            <td colspan="6" class="text-muted text-right">
              <span class="mr-3">
                本期累计还款金额：
                <span class="text-primary">{{ item.info.repay_funds_total }}</span>
                元
              </span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <repay-edit
      :visible.sync="editVisible"
      @success="handleSuccess"
      :form-data="formData"
      :table-id="tableId"
      :query-id="queryId"
    ></repay-edit>

    <el-dialog :visible.sync="viewVisible" append-to-body title="还款附件">
      <div v-for="(file, index) of attachs" :key="index">
        <attach-item :attach-data="file"></attach-item>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import RepayEdit from '@/credit/views/city/self/after/repay/RepayEdit'
import { sub } from '@vimi/utils-tool'
import { arrayFromString } from '@vimi/utils-tool'
import AttachItem from '@/bank/components/attach/Item'
import { attachAdapter } from '@/bank/components/attach/index'
export default {
  components: {
    RepayEdit,
    AttachItem,
  },
  props: {
    queryId: String,
  },
  data() {
    return {
      sub,
      loading: false,
      tableName: 'repay_register',
      editVisible: false,
      tableData: [],
      tableId: '',
      formData: {},
      leftFunds: '',
      related: {},
      viewVisible: false,
      attachs: [],
      idsData: [],
      hasPlan: false,
    }
  },
  computed: {
    ...mapGetters(['user']),
  },
  watch: {
    queryId: {
      handler: function (val) {
        if (val) {
          this.getData()
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getPlan()
  },
  mounted() {},
  methods: {
    getPlan() {
      this.$api
        .getData(this.$serviceName, 'datum_repay_list', {
          'customer_related_id.eq': this.queryId,
          index: 1,
          size: 1,
        })
        .then(res => {
          const data = res?.data?.data ?? []
          this.hasPlan = !!data.length
        })
    },
    handleView(row) {
      this.attachs = arrayFromString(row.attachment).map(item => {
        return attachAdapter({ attachment: item })
      })
      this.viewVisible = true
    },
    handleSuccess() {
      this.getData()
      this.$emit('success', true)
    },
    handleDelete(row = {}) {
      this.$utils
        .msgbox({
          message: `确定删除${row.repay_time}的还款信息?`,
          beforeClose: () =>
            this.$api.deleteData(this.$serviceName, this.tableName, row.repay_register_id),
        })
        .then(() => {
          this.handleSuccess()
          this.$message.success('删除成功！')
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '删除失败！')
        })
    },
    async getData() {
      this.leftFunds = 0
      this.loading = true
      await this.$api
        .getData(this.$serviceName, 'customer_related', {
          'customer_related_id.eq': this.queryId,
          fields: ['left_funds', 'load_beh_status'],
        })
        .then(res => {
          const data = res?.data?.[0] ?? {}
          this.related = { ...data }
          this.leftFunds = data.left_funds
        })
      this.$api
        .getData(
          this.$serviceName,
          this.tableName,
          {
            'customer_related_id.eq': this.queryId,
            subKey: 'datum_repay_list_view_new.datum_repay_list_id',
          },
          {
            repay_time: 'desc',
          }
        )
        .then(res => {
          const data = res?.data ?? []
          this.tableData = data
          const idsData = []
          data.forEach(item => {
            const inData = idsData.find(i => i.id === item.datum_repay_list_id)
            if (inData) {
              inData?.data.push(item)
            } else {
              idsData.push({
                id: item.datum_repay_list_id,
                info: item.datum_repay_list_view_new?.[0] ?? {},
                data: [item],
              })
            }
          })
          this.idsData = idsData
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleEdit(row) {
      this.tableId = row?.repay_register_id ?? ''
      this.formData = row ? { ...row } : {}
      this.editVisible = true
    },

    handleBeforeSave(model) {
      model.submit_person_name = this.user.realName
      model.customer_related_id = this.queryId
      return model
    },
  },
}
</script>

<style lang="scss" scoped></style>
